﻿var _this = this;
var popup=false;
var watchClose;
var checkBoxOptionEnum = {
        SHOW:1,
        HIDE:2,
        HIDEFAST:3,
        CHECKALL:4,
        UNCHECKALL:5,
        CHECKOUT:6
};




$(document).ready(function() {
	personBtnHide();
	loadAddressBookTree();
	_this.table1 = tableSync('tbl1');
	$('#userDetailView').hide();
	$('#tbl1').hide();
	$('#btn_search').click(function() {
		searchBtn($('#input_search').val());
		
//		pezAlert("test");

	});
	popup.closed=true;	
	bindingPersonBtn();
	CheckBox(checkBoxOptionEnum.HIDE);

//	$(".confirm").easyconfirm();
//	$("#yesBtn").click(function() {
//		
//	});
	
	
	// 친구 테이블에서 전체 check box 클릭
	$('#th_input_chkbox').click(function(){
		if($('#th_input_chkbox').attr("checked")=='checked'){
			CheckBox(checkBoxOptionEnum.CHECKALL);	
		}else{
			CheckBox(checkBoxOptionEnum.UNCHECKALL);	
		}
		
	});
	
});

function removeFriends(){
	var param={};
	$('#tbl1 tbody tr').each(function(index) {
//		console.log('aaaa index='+index);
		if($(this).find('#tr_input_chkbox').attr("checked")=='checked'){
			param['list'+index]=$(this).find('#nSeq').text();
		}
	});
	$.post('remove_person_action.json', param, function(data) {
		try{
			
			location.reload();
			pezAlert("완료!!");
		}catch(eInner){
			errLog(eInner);
		}
	});
	
}

function CheckBox(option){
	switch(option){
	case checkBoxOptionEnum.SHOW:{
//		console.log('show 1121dd11');
		try{
//			$('#th_chkbox').removeAttr("style");
//			$('#th_chkbox').show();
			$('#th_chkbox').fadeIn();
			$('#tbl1 tbody tr').each(function() {
//				$(this).find('#tr_chkbox').animate({width: 80}, 1500);
//				$(this).find('#tr_chkbox').show();
				$(this).find('#tr_chkbox').fadeIn();
//				$(this).find('#tr_chkbox').removeAttr("style");
			});
		}catch(e){
			errLog(e);
		}
		
		break;
	}
	case checkBoxOptionEnum.HIDE:{
//		console.log('HIDE 2k2d1');
		try{
//			$('#th_chkbox').hide();
			$('#th_chkbox').fadeOut();
//			$('#th_chkbox').attr("style","display:none");
			$('#tbl1 tbody tr').each(function() {
//				$(this).find('#tr_chkbox').attr("style","display:none");
//				$(this).find('#tr_chkbox').animate({width: 0}, 1500);
//				$(this).find('#tr_chkbox').hide();
				$(this).find('#tr_chkbox').fadeOut();
//				$(this).find('#tr_chkbox').animate({"style":"display:none"}, 1000, 'swing');
			});	
		}catch(e){
			errLog(e);
		}
			
		break;
	}	
	case checkBoxOptionEnum.HIDEFAST:{
//		console.log('HIDEFAST 2k2d1');
		try{
			$('#th_chkbox').hide();
//			$('#th_chkbox').fadeOut();
//			$('#th_chkbox').attr("style","display:none");
			$('#tbl1 tbody tr').each(function() {
//				$(this).find('#tr_chkbox').attr("style","display:none");
//				$(this).find('#tr_chkbox').animate({width: 0}, 1500);
				$(this).find('#tr_chkbox').hide();
//				$(this).find('#tr_chkbox').fadeOut();
//				$(this).find('#tr_chkbox').animate({"style":"display:none"}, 1000, 'swing');
			});	
		}catch(e){
			errLog(e);
		}
			
		break;
	}	
	case checkBoxOptionEnum.CHECKALL:{
//		console.log('CHECKALL 123466');
		try{
			
			$('#tbl1 tbody tr').each(function() {
//				$(this).find('#tr_chkbox').hide();
//				console.log('CHECKALL 111'+($(this).find('#tr_input_chkbox').attr("checked")=='checked'));
				if(!($(this).find('#tr_input_chkbox').attr("checked")=='checked')){
					$('#tbl1 tbody tr').each(function() {
//						console.log('CHECKALL 1333');
						$(this).find('#tr_input_chkbox').attr('checked', 'checked');
					});
					return 0;	// break;
				};
			});	
		}catch(e){
			errLog(e);
		}
			
		break;
	}	
	case checkBoxOptionEnum.UNCHECKALL:{
//		console.log('UNCHECKALL 111');
		try{
			
			$('#tbl1 tbody tr').each(function() {
				$(this).find('#tr_input_chkbox').removeAttr('checked');
			});	
		}catch(e){
			errLog(e);
		}
			
		break;
	}	
	/**
	 * 체크된게 하나라도 있으면 return false;<br/>
	 * 체크된게 없으면 return true;
	 * checkbox가 hide 상태이면 return null;
	 */
	case checkBoxOptionEnum.CHECKOUT:{
//		console.log('CHECKOUT 22');
		try{
			if(getCheckBoxVisibleStatus()) return null;
			var ret = true;
			$('#tbl1 tbody tr').each(function() {
				if(($(this).find('#tr_input_chkbox').attr("checked")=='checked')){
//					console.log("CHECKOUT return false");
					ret = false;
					return true;	// break;
				}
			});	
//			console.log("CHECKOUT return true");
			return ret;
		}catch(e){
			errLog(e);
		}
			
		break;
	}	
	
	
	default:{
//		console.log('default 11321');
		try{
//			if(toggle==1){
//				toggleCheckBox(checkBoxOptionEnum.SHOW);
//				toggle=2;
//			}else{
//				toggleCheckBox(checkBoxOptionEnum.HIDE);
//				toggle=1;
//			}
			var attr = $('#th_chkbox').attr('style');
//			console.log('default 1q121 '+attr);
//			if (typeof attr !== 'undefined' && attr !== false) {	//hide 상태
			if(getCheckBoxVisibleStatus()){
				CheckBox(checkBoxOptionEnum.SHOW);
			}else{	// show 상태
				CheckBox(checkBoxOptionEnum.HIDE);
			}
		}catch(e){
			errLog(e);
		}
		break;
	}
	}
}

/**
 *	숨어 있으면 return true;<br/>
 *	show 상태이면 return false; 
 * @returns {Boolean}
 */
function getCheckBoxVisibleStatus(){
	var attr = $('#th_chkbox').attr('style');
	
//	console.log('default 1q121 '+attr);
//	if (typeof attr !== 'undefined' && attr !== false) {	//hide 상태
	if(typeof attr !== 'undefined' &&(attr.indexOf("none")>0)){
		return true;
	}else{	// show 상태
		return false;
	}
}

function setEventPopupClosed(){
	try{
		watchClose = setInterval(function() {
			if (popup.closed) {
				clearTimeout(watchClose);
//				pezAlert("aaaaaaaaaaaa");
				location.reload();
			} 
		}, 400);	
	}catch(e){
		errLog(e);
	}
}



function bindingGroupBtn(){
	$('#add_group').click(function(){
		try{
			if(popup.closed==undefined||popup.closed){
				var selectedSeq = getSelectedTreeId();
				var url = "popup/add_group?seq="+selectedSeq;
				popup = openCenterWindow( 400, 150, url);
				setEventPopupClosed();
			}
		}catch(e){
			errLog(e);
		}
	});
	
	
	$('#remove_group').click(function(){
		try{
			if(popup.closed==undefined||popup.closed){
	
				var selectedOne = $('#depart_tree').find('.jstree-clicked');
				var selectedSeq = selectedOne.parent().attr('id');
				
				var hasChild =selectedOne.next().children('li').attr('id'); 
				if(selectedOne.length==0){
					pezAlert('삭제할 그룹을 고르세요.');
					return;
				}else 	
				if(hasChild==undefined){
//					console.log("has No Child!! ");	
				}		
				else{
					pezAlert('하위 그룹이 있을 경우는 삭제할 수 없습니다.\n하위 그룹을 먼저 삭제해주세요.');
					return;
				}
				
				var url = "popup/remove_group?seq="+selectedSeq;
				
				popup = openCenterWindow( 400, 150, url);
				setEventPopupClosed();
			}
		}catch(e){
			errLog(e);
		}
	});
	$('#modify_group').click(function(){
		try{
			if(popup.closed==undefined||popup.closed){
				var selectedOne = $('#depart_tree').find('.jstree-clicked');
				var selectedSeq = selectedOne.parent().attr('id');
	//			console.log(selectedSeq);
	//			console.log(null == selectedSeq);
				if(null == selectedSeq){
	//				pezAlert("aaaaaaaaaaaaa");
					if($('#depart_tree').find('li').length>0){
						var url = "popup/modify_group?seq="+selectedSeq;
						popup = openCenterWindow( 400, 150, url);
						setEventPopupClosed();	
					}else{
						pezAlert("그룹이 하나도 없습니다.");
					}
				}else{
					var url = "popup/modify_group?seq="+selectedSeq;
					popup = openCenterWindow( 400, 150, url);
					setEventPopupClosed();	
				}
			}
		}catch(e){
			errLog(e);
		}
	});
}


function bindingPersonBtn(){
	$('#add_person').click(function(){
		try{
			if(popup.closed==undefined||popup.closed){
				var selectedSeq = getSelectedTreeId();
				var url = "popup/add_person?seq="+selectedSeq;
				popup = openCenterWindow(500, 500, url, "add_person");
//				popup = openCenterNewWindow("add_person", 500, 500, url);
				setEventPopupClosed();
			}
		}catch(e){
			errLog(e);
		}
	});
	
	
	$('#remove_person').click(function(){
		try{
			if(getCheckBoxVisibleStatus()){	// 숨겨진 상태면 나타내기
				CheckBox(checkBoxOptionEnum.SHOW);	
			}else{
				if(CheckBox(checkBoxOptionEnum.CHECKOUT)){
					CheckBox(checkBoxOptionEnum.HIDE);	
				}else{
					// 삭제 컨펌 버튼
					
//					new pezAlertClass($('#yesBtn').text(), function(){
//						removeFriends();
//					}).type(alertType.CONFIRM).show();
					pezAlert($('#yesBtn').text(), function(){
						removeFriends();
					}).type(alertType.CONFIRM).show();
				}
			}
			
			
			
			
			
			
			
//			if(popup.closed==undefined||popup.closed){
//				var gSeq = getSelectedTreeId();
//				var nSeq = getSelectedPersonId();
//				console.log("remove_person click nSeq="+nSeq);
//				var url = "popup/remove_person?gseq="+gSeq+"&nseq="+nSeq;
//				popup = openCenterWindow( 500, 500, url);
//				setEventPopupClosed();
//			}
		}catch(e){
			errLog(e);
		}
	});
	$('#modify_person').click(function(){
		try{
			if(popup.closed==undefined||popup.closed){
				var selectedSeq = getSelectedTreeId();
				
				var nSeq = $('.table_clicked').find('#nSeq').text();
//				console.log('modify_person  11');
//				console.log(nSeq);
				if(nSeq.length==0){
					pezAlert("선택된 사람이 없습니다.");
					return;
				}
				
				var url = "popup/modify_person?seq="+selectedSeq+"&nSeq="+nSeq;
				popup = openCenterWindow( 500, 500, url, "modify_person");
				setEventPopupClosed();	
				
			}
		}catch(e){
			errLog(e);
		}
	});
}


function personBtnHide(){
//	$('#add_person').hide();
	$('#remove_person').hide();
	$('#modify_person').hide();
}

function personBtnShow(){
	$('#add_person').show();
	$('#remove_person').show();
	$('#modify_person').show();
}

function searchBtn(data){
//	console.log("searchBtn data="+data);
	try{
		if(data.length>0){
			$('#tbl1 tbody tr').each(function() {
				var show=false;
				var trItem = $(this);
	//			console.log($(this).html()+'--html()');
				$(this).find('td').each(function(){
					
	//				console.log($(this).attr('id')+'--id html()');
					if($(this).attr('id')=="username")
						return true;//continue
					var text = $(this).text();
	//				console.log(text+", "+text.indexOf(data));
					if(text.indexOf(data)>=0){
						show=true;
					}
				});
				if(show){
					trItem.show();	
				}else{
					trItem.hide();	
				}
				
			});	
		}else{
			$('#tbl1 tr').each(function() {
				$(this).show();
			});
		}
	}catch(e){
		errLog(e);
	}
}


// 트리 그리기
function loadAddressBookTree(){
	try{
		$("#depart_tree").bind("loaded.jstree",
				function(e, data) {
					data.inst.open_all(-1);
				}).jstree({
			"plugins" : [ "themes", "html_data", "ui" ]
		}).delegate("a", "click", function(event, data) {
			event.preventDefault();
		}).bind("select_node.jstree", function(event, data) {
	//		var department_code = data.rslt.obj.attr("id");
	//		department_getMemberInGroup(department_code);
			var department_obj = data.rslt.obj;
			

			department_getMemberInGroup(department_obj);
			
	//		console.log(child);
		});
		bindingGroupBtn();
	}catch(e){
		errLog(e);
	}
}

function getChild(obj){
	try{
		child.push(obj.attr('id'));
//		console.log("obj.attr('id')="+obj.attr('id'));
		jQuery.each(obj.find('li'), function(index){
//			log("index = "+index);
//			log($(this));
//			log("id= "+$(this).attr('id'));
			child.push($(this).attr('id'));
//			getChild(ele);
		});
	}catch(e){
		errLog(e);
	}
}

// 트리 온클릭
var child= [];
function department_getMemberInGroup(department_obj) {
	try{
		child= [];
		getChild(department_obj);
		
		var param={};
		
		for(var i=0;i<child.length;i++){
			param["group_list"+i]=child[i];
		}
		
//		console.log('department_getMemberInGroup 12222');
		
		$.post('friendList.json', param, function(data) {
			try{
				if(data.list.length==0){
					$('#tbl1 tbody').hide();
				}else{
					$('#tbl1 tbody').show();
					$('#tbl1 tr').each(function() {
						$(this).show();
					});
				}
				
				_this.table1.tableAutoSync(data.list,  syncOptionEnum.clearValues);
				tableClickedCSS('tbl1');
				// 테이블 tr 클릭
				$('#tbl1 tbody tr').click(function(){
					tableClickedCSS('tbl1', this);
					showUserInfo($(this).find('#nSeq').text());
					if($(this).find('#tr_input_chkbox').attr('checked')!='checked'){
						$('#th_input_chkbox').removeAttr('checked');
					}
					
					
				});
				$('#tbl1').show();
				personBtnShow();	// 친구 목록을 가지고 왔을 때 버튼이 나타난다.
				CheckBox(checkBoxOptionEnum.HIDEFAST);
			}catch(eInner){
				errLog(eInner);
			}
		});
	}catch(e){
		errLog(e);
	}
}

function tableClickedCSS(tableId, clickedTr){
//	console.log($(clickedTr));
	$('#'+tableId+' tbody tr').each(function() {
		$(this).removeClass("table_clicked");
	});
	$(clickedTr).addClass("table_clicked");
}

function showUserInfo(nSeq){
	try{
		var param = {"nSeq" : nSeq};
//		console.log("showUserInfo = "+nSeq);
		$.post('showfriendinfo.json', param, function(data) {
			try{
//				console.log(JSON.stringify(data));
//				console.log(JSON.stringify(data.dat));
				
				var rank = data.dat.rank;
				if(rank==null) rank="";
				var level = data.dat.level;
				if(level==null) level="";
				var position_name = rank+" / "+level;
				data.dat.position_name = position_name;
				
				if(data.dat.email_name!=null){
					var email = data.dat.email_name+"@"+data.dat.email_address;
					data.dat.email = email;	
				}
				
				if(data.dat.office_number1!=null){
					var office_number = data.dat.office_number1+"-"+data.dat.office_number2+"-"+data.dat.office_number3;
					if(data.dat.office_number4!=undefined){
						office_number+="("+data.dat.office_number4+")";
					}
					data.dat.office_number = office_number;	
				}
				
				if(data.dat.fax_number1!=null){
					var fax_number = data.dat.fax_number1+"-"+data.dat.fax_number2+"-"+data.dat.fax_number3;
					data.dat.fax_number = fax_number;	
				}
				
				if(data.dat.cell_number1!=null){
					var cell_number = data.dat.cell_number1+"-"+data.dat.cell_number2+"-"+data.dat.cell_number3;
					data.dat.cell_number = cell_number;	
				}
				
				if(data.dat.messenger_name!=null){
					var messenger = data.dat.messenger_name+"@"+data.dat.messenger_address;
					data.dat.messenger = messenger;	
				}
				
				var zipcode1 = data.dat.zipcode1;
				var zipcode2 = data.dat.zipcode2;
				var address1 = data.dat.address1;
				var address2 = data.dat.address2;
				if(zipcode1==null) zipcode1="";
				if(zipcode2==null) zipcode2="";
				if(address1==null) address1="";
				if(address2==null) address2="";
				var address = "("+zipcode1+"-"+zipcode2+")"+address1+" "+address2;
				
				data.dat.address = address;
				
				if(data.dat.profile_img_seq==0){
					data.dat.profile_img_seq=getContextPath()+"/resources/images/no_image.jpg";
				}else{
					data.dat.profile_img_seq=getContextPath()+"/attachment/download/"+data.dat.profile_img_seq;
				}
				
				autoSync("userDetailView", data.dat, syncOptionEnum.clearValues);
				
				$('#userDetailView').show();
			}catch(eInner){
				errLog(eInner);
			}
		});	
	}catch(e){
		errLog(e);
	}
}

function getSelectedTree(){
	return $('#depart_tree').find('.jstree-clicked');
}

function getSelectedTreeId(){
	return getSelectedTree().parent().attr('id');
}
function getSelectedPerson(){
	return $('#tbl1').find('.table_clicked');
}

function getSelectedPersonId(){
	return getSelectedPerson().find('#nSeq').text();
}
function errLog(e){
	console.log(e);
}